import { resolve, join } from 'path'
import { realpathSync } from 'fs'
import ci from 'miniprogram-ci'
import { readJsonSync } from 'fs-extra'
import chalk from 'chalk'
import { createLogger } from '../logger'

const cwd = process.cwd()
const projectPath = realpathSync(cwd)
const packageJson = readJsonSync(join(cwd, 'package.json'))

const logger = createLogger('info', { prefix: '[Uploader]' })

export const run = (appid: string, key: string) => {
  const project = new ci.Project({
    appid,
    type: 'miniProgram',
    projectPath: resolve(projectPath, './dist'),
    privateKeyPath: `${key}/private.${appid}.key`,
    ignores: ['node_modules/**/*', 'src/**/*', 'public/**/*', 'scripts/**/*']
  })

  ci.upload({
    project,
    version: packageJson.version,
    desc: packageJson.versionDesc,
    setting: {
      es6: true,
      minify: true,
      minifyJS: true,
      minifyWXML: true,
      minifyWXSS: true,
      autoPrefixWXSS: true,
      es7: true
    },
    onProgressUpdate: task => typeof task === 'string' ? logger.info(task) : ''
  }).then(() => {
    process.exit(0)
  }).catch((e) => {
    logger.error(chalk.red(e))
    process.exit(1)
  })
}
